import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:series_play/widget/app_text.dart';

class VideoExpandableText extends StatefulWidget {
  final String text;
  final int maxLines;
  final TextStyle? style;
  final String expandText;
  final String collapseText;
  final Color? buttonColor;

  const VideoExpandableText({
    super.key,
    required this.text,
    this.maxLines = 2,
    this.style,
    this.expandText = '展开',
    this.collapseText = '收起',
    this.buttonColor,
  });

  @override
  State<VideoExpandableText> createState() => _VideoExpandableTextState();
}

class _VideoExpandableTextState extends State<VideoExpandableText> {
  bool _expanded = false;
  bool _overflow = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _checkOverflow();
  }

  void _checkOverflow() {
    final textSpan = TextSpan(text: widget.text, style: widget.style);
    final tp = TextPainter(
      text: textSpan,
      maxLines: widget.maxLines,
      textDirection: TextDirection.ltr,
    );
    tp.layout(maxWidth: MediaQuery.of(context).size.width);
    setState(() {
      _overflow = tp.didExceedMaxLines;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        // 让文本部分占满剩余空间
        Expanded(child: AppText.videoShadowSecondary(
          widget.text,
          maxLines: !_expanded ? widget.maxLines : null,
          textOverflow: !_expanded ? TextOverflow.ellipsis : null,
        )),

        Visibility(
          visible: _overflow,
          child: Padding(
            padding: const EdgeInsets.only(left: 8).r,
            child: GestureDetector(
              onTap: () => setState(() => _expanded = !_expanded),
              child: AppText.videoShadowSecondary(
                _expanded ? widget.collapseText : widget.expandText,
                color: widget.buttonColor ?? Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
